/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormCliente.java
 *
 * Created on 29/08/2011, 17:56:40
 */
package javalee.forms;

import javalee.maps.Cliente;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javalee.util.Uteis;
import javalee.dao.*;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Thiago
 */
public class FormCliente extends javax.swing.JFrame {
    
    private clienteDAO cliDAO;

    /** Creates new form FormCliente */
    public FormCliente() {
        initComponents();
        cliDAO = new clienteDAO();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnSalvar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        btnFechar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtPesquisa = new javax.swing.JTextField();
        txtCliente = new javax.swing.JTextField();
        txtId = new javax.swing.JTextField();
        btnLimpar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbConsulta = new javax.swing.JTable();

        setTitle("Formulario de Clientes");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Nome do cliente : ");

        jLabel2.setText("ID do cliente : ");

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnRemover.setText("Excluir");
        btnRemover.setEnabled(false);
        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });

        btnFechar.setText("Fechar");
        btnFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharActionPerformed(evt);
            }
        });

        jLabel3.setText("Pesquisar cliente :");

        txtPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPesquisaActionPerformed(evt);
            }
        });
        txtPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPesquisaKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtPesquisaKeyTyped(evt);
            }
        });

        txtId.setEditable(false);
        txtId.setEnabled(false);
        txtId.setFocusable(false);

        btnLimpar.setText("Limpar dados");
        btnLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparActionPerformed(evt);
            }
        });

        tbConsulta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Id", "Nome"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbConsulta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbConsultaMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tbConsultaMouseReleased(evt);
            }
        });
        jScrollPane2.setViewportView(tbConsulta);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addGap(2, 2, 2))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(2, 2, 2)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(82, 82, 82)
                                        .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(btnLimpar)
                                    .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 136, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 92, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 409, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(btnRemover)))
                                .addGap(12, 12, 12)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnFechar, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(20, 20, 20))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(btnLimpar))
                    .addComponent(btnRemover))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSalvar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnFechar, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
    if(ValidarForm())
    {
    
    try {
        int row = tbConsulta.getSelectedRow();
        boolean sucesso = false;
        
        Cliente cliNovo = new Cliente();
        if(row == -1){
            cliNovo.setNome(txtCliente.getText());
            if (cliDAO.cadastrar(cliNovo)) {
                JOptionPane.showMessageDialog(null, "Cliente cadastrado.");
                txtCliente.setText("");
            } else {
                JOptionPane.showMessageDialog(null, "Problema ao cadastrar cliente.");
            }
        }else{
            cliNovo.setId(Integer.parseInt(txtId.getText()));
            cliNovo.setNome(txtCliente.getText());
            if (cliDAO.alterar(cliNovo)) {
                JOptionPane.showMessageDialog(null, "Cliente alterado.");
            } else {
                JOptionPane.showMessageDialog(null, "Problema ao alterar cliente.");
            }
        }
        preencheDados();

    } catch (Exception e) {
        System.out.println(e.toString());
    }
    }
}//GEN-LAST:event_btnSalvarActionPerformed

private void txtPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPesquisaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPesquisaActionPerformed

private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
    int row = tbConsulta.getSelectedRow();
    
    if(tbConsulta.getSelectedRow()==-1){
        JOptionPane.showMessageDialog(null,"Selecione um Cliente para Excluir.");
        btnRemover.setEnabled(false);
    }
    else{
    DefaultTableModel tableModel = (DefaultTableModel)tbConsulta.getModel();  
    Cliente cliEx = new Cliente(Integer.parseInt(tableModel.getValueAt(row, 0).toString()));
    
    if(JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir o cliente?","Confirmação!",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
        if( cliDAO.excluir(cliEx) ){
            JOptionPane.showMessageDialog(null,"Cliente Excluído com sucesso.");
            txtPesquisa.setText("");
        } else {
            JOptionPane.showMessageDialog(null,"Problema ao excluir o cliente.");
        }
    }
    limpaDados();
    preencheDados();// TODO add your handling code here:
    }
}//GEN-LAST:event_btnRemoverActionPerformed

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    preencheDados();
}//GEN-LAST:event_formWindowOpened

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
//    preencheDados();
}//GEN-LAST:event_formWindowGainedFocus

private void txtPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPesquisaKeyReleased
    if(evt.getKeyCode()==10){
        
        preencheDados();
    }
}//GEN-LAST:event_txtPesquisaKeyReleased

private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
    tbConsulta.clearSelection();
    limpaDados();
}//GEN-LAST:event_btnLimparActionPerformed

private void btnFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharActionPerformed
    try {
        formWindowClosed(null);
    } catch (Exception e) {
    }
}//GEN-LAST:event_btnFecharActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    setVisible(false);
}//GEN-LAST:event_formWindowClosed

private void tbConsultaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbConsultaMouseReleased
    int row = tbConsulta.getSelectedRow();
    
    DefaultTableModel tableModel = (DefaultTableModel)tbConsulta.getModel();  
    txtId.setText(tableModel.getValueAt(row, 0).toString());
    txtCliente.setText(tableModel.getValueAt(row, 1).toString());
}//GEN-LAST:event_tbConsultaMouseReleased

private void tbConsultaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbConsultaMouseClicked
    btnRemover.setEnabled(true);
    // TODO add your handling code here:
}//GEN-LAST:event_tbConsultaMouseClicked

private void txtPesquisaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPesquisaKeyTyped
      
    // TODO add your handling code here:
}//GEN-LAST:event_txtPesquisaKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FormCliente().setVisible(true);
            }
        });
    }
    
   
    
    private void preencheDados()
    {
        if(!Uteis.validaCampoTexto(txtPesquisa)){
            JOptionPane.showMessageDialog(null,"Campo de pesquisa está incorreto.");
        }
        else{
        //Trago a lista de clientes do banco
        ArrayList<Cliente> lista = cliDAO.consultar(txtPesquisa.getText().toString());
        tbConsulta.removeAll();
     
        //Pego o TableModel do componente JTable
        DefaultTableModel tableModel = (DefaultTableModel)tbConsulta.getModel();  
        //Limpo os dados do componente
        tableModel.setNumRows(0);
     
        //Passo pela lista de Clientes, inserindo no JTable
        for(Iterator<Cliente> it = lista.iterator(); it.hasNext();){
            Cliente c = (Cliente)it.next();
            tableModel.addRow(new Object[]{
                c.getId(),//Cada campo que coloco vira uma coluna
                c.getNome()
            });     
        }
        }
    }
    
    private void limpaDados()
    {
        txtId.setText("");
        txtCliente.setText("");
    }
    
    private boolean ValidarForm()
    {
        boolean valido = true;
        
        if(txtCliente.getText().trim().length()<=2)
        {
            valido = false;
            JOptionPane.showMessageDialog(null,"Nome do cliente inválido.");
        }
        else if(!Uteis.validaCampoTexto(txtCliente)){
            valido = false;
            JOptionPane.showMessageDialog(null,"Nome do cliente inválido.");
        }
        return valido;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnFechar;
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnRemover;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable tbConsulta;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtPesquisa;
    // End of variables declaration//GEN-END:variables
}
